package com.opensns.test;

import org.json.JSONObject;

import com.opensns.android.OauthAccessToken;
import com.opensns.android.Parameters;
import com.opensns.sinaweibo.SinaWeibo;


public class SinaWeiboActivity extends TestActivty {
	
	@Override
	protected void onInit() {
		super.onInit();
		
		SinaWeibo.APP_KEY = "396826960";
		SinaWeibo.CALLBACK_URL = "http://www.sina.com";
		mSina = SinaWeibo.getInstance();
		
		mToken = SinaWeibo.restoreAccessToken(this);
		if (OauthAccessToken.isTokenValid(mToken)) {
			mSina.setAccessToken(mToken);
			updateTokenInfo(mToken);
		}
	}

	@Override
	protected void callAuthorize() {
		if (mToken == null) {
			mSina.authorize(getActivityContext(), mAuthCallback);
		}
	}

	@Override
	protected void onAuthorizeSuccess() {
		mToken = mSina.getAccessToken();
		SinaWeibo.storeAccessToken(getActivityContext(), mToken);
		updateTokenInfo(mToken);
	}

	@Override
	protected void sendGetUserNameRequest() {
		if (mToken != null) {
			Parameters params = new Parameters();
			params.add("access_token", mToken.accessToken);
			params.add("uid", mToken.uid);
			mSina.requestAsync(this, "users/show.json", params, "GET", mGetNameCallback);
		}
	}

	@Override
	protected String getUserNameFromResponse(String response) {
		try {
			JSONObject result = new JSONObject(response);
			return result.optString("name");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void publishContent(String text) {
		if (mToken != null) {
			Parameters params = new Parameters();
			params.add("access_token", mToken.accessToken);
			params.add("status", text);
			mSina.requestAsync(getActivityContext(), "statuses/update.json", params, "POST", mPublishCallback);
		}
	}

	SinaWeibo mSina;
	OauthAccessToken mToken;
}
